package com.semptian.security.service;

import com.google.code.kaptcha.Constants;
import com.semptian.security.exception.MyAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zww
 * @date 2018-05-01 22:22
 * <p>
 * Email 971762302@qq.com
 * <p>
 * Describe:
 */
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        //这里可以抛出继承自AuthenticationException的exception
        //然后会转到MyAuthenticationFailureHandler。
        //比如说验证码什么的可以在这里验证，然后抛出异常。
        //然后让MyAuthenticationFailureHandler去处理，并输出返回

        //下面的代码段是具体的示例
        //当用户输入的用户名为“123”抛出自定义的AuthenticationException异常。
        String kaptcha = request.getParameter("kaptcha");
        String KAPTCHA_SESSION_KEY = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(!KAPTCHA_SESSION_KEY.equals(kaptcha))
        {
            throw new MyAuthenticationException("验证码错误");

        }

        return super.attemptAuthentication(request, response);
    }
}
